<template>
  <div>
    <n-card :bordered="false" class="proCard table">
      <div class="top-tools">
        <n-space>
          <n-button type="primary" secondary @click="downloadExcelFile">导出Excel</n-button>
          <n-button type="info" secondary @click="(showModal = true)">导入Excel</n-button>
        </n-space>
      </div>
      <n-data-table
      :columns="columns"
      :data="data"
      :cascade="false"
      :row-key="(row) => row.id"
      allow-checking-not-loaded
      @load="onLoad"
    />
    </n-card>
    <n-modal
      v-model:show="showModal"
      preset="card"
      title="上传Excel文件"
      style="width: 600px;"
      >
      <n-upload
        :custom-request="excelDictFileUpload"
        >
        <n-upload-dragger>
          <div style="margin-bottom: 12px">
            <n-icon size="48" :depth="3">
              <archive-icon />
            </n-icon>
          </div>
          <n-text style="font-size: 16px">
            点击或者拖动文件到该区域来上传
          </n-text>
          <n-p depth="3" style="margin: 8px 0 0 0">
            请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
          </n-p>
        </n-upload-dragger>
      </n-upload>
    </n-modal>
  </div>
</template>
<script setup>

import { findChildData, uplodExcelDictFile, downloadExcelDictFile } from "@/api/dict";
import { onMounted, ref } from "vue";
import { UploadOutlined as ArchiveIcon } from '@vicons/antd'


const data = ref([])
const showModal = ref(false)
const columns = [
  { 
    type: 'selection' 
  },
  { 
    key: 'name', 
    title: '名称' 
  },
  { 
    key: 'value', 
    title: '值' 
  },
  { 
    key: 'dictCode', 
    title: '字典代码' 
  },
  {
    key: 'createTime',
    title: '创建时间'
  }
]

onMounted(() => {
  loadDataTable()
})

const loadDataTable = async () => {
  data.value = await findChildData(1)
}

const onLoad = (row) => {
  return new Promise(async (resolve, reject) => {
    try {
      row.children = await findChildData(row.id)
      return resolve();
    } catch (error) {
      return reject(e);
    }
  })
}

const downloadExcelFile = () => {
  downloadExcelDictFile()
}

// 自定义文件上传方法
const excelDictFileUpload = async ({ file, onFinish, onProgress, onError }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  uplodExcelDictFile(formData, {
    onUploadProgress: ({ percent }) => {
      onProgress({ percent: Math.ceil(percent) });
    },
  }).then(() => {
    // 上传成功
    // 刷新表格
    loadDataTable()
    setTimeout(() => {
      showModal.value = false
    }, 500)
    onFinish()
  }).catch(() => {
    onError()
  });
}
</script>
<style scoped lang="less">
.top-tools {
  margin-bottom: 15px;
}
</style>